$(window).load(function(){
	$(".tabs-nav-item").click(function(){
		$(".tabs-nav-item").removeClass("current");
		$(this).addClass("current");
		$(".tabs-item").hide();
		$("#"+this.getAttribute("id")+"-content").show();
	});
	$.each(window['bgWindow']['oCatogories'], function(i, cat){
		if(typeof cat != 'undefined' && cat){
			if(!$("ul[category='"+cat['category']+"']").length){
				$("#catTree").append(
					$("<li />").append(
						$('<input type="checkbox" ></input>').hide()
					).append(
						$("<h2 />").text(cat['category'])
					).append(
						$("<ul />").attr("category", cat['category'])
					)
				);
			}
			
			$("ul[category='"+cat['category']+"']").append(
				$("<li />").append(
					$('<input type="checkbox" ></input>').attr("catId", i).bind("change", function(e){
						window['bgWindow']['oCatogories'][i]['checked'] = this.checked;
					})['setChecked'](cat['checked'])
				).append(
					$("<label />").text(cat['label'])
				)
			);
		}
	});
	
	function submitToExceptions(){
		var id = this.getAttribute('id');
		if($("#"+id+"Domain").val()){
			//console.log(this, this.id, this.getAttribute('id'))
			if(checkDomainExists($("#"+id+"Domain").val())){
				alert("Домен уже в списке");
			} else {
				var res = checkDomainValid($("#"+id+"Domain").val());
				if(res){
					window['bgWindow']['oExceptions'][id].push({'url': res});
					window['bgWindow']['oExceptions'].save();
					$("#"+id+"Domain").val('');
					renderExceptionsTable(id);
				} else {
					alert("Невалидный домен");
				}
			}
		}
	}
	
	$(".submitToExceptions").click(submitToExceptions);
	$(".submitToExceptionsInput").keypress(function(aEvent){
		if (aEvent.which == '13') {
			submitToExceptions.apply(document.getElementById((this.getAttribute("id")=='whitelistDomain')?'whitelist':'blacklist'));
		}
	})
	
	function checkDomainValid(url){
		var res =  /([а-яa-z0-9]+([\-\.]{1}[а-яa-z0-9]+)*\.[а-яa-z]{2,5})(?:\/.*)?$/i.exec(url);
		return  (res)?res[0]:res;
	}
	
	function checkDomainExists(url){
		var res = false,
			cats = ['whitelist', 'blacklist'];
		for(j in cats){
			console.log(window['bgWindow']['oExceptions'][cats[j]]);
			for (i in window['bgWindow']['oExceptions'][cats[j]]){
				var item = window['bgWindow']['oExceptions'][cats[j]][i];
				console.log(item);
				if (item['url'] == url){
					res = true;
					break;
				}
			}
			if(res)
				break;
		}
		return res;
	}

	renderExceptionsTable('whitelist');
	renderExceptionsTable('blacklist');
	
	$("#catTree")['checkboxTree']({
		'initializeChecked': 'expanded',
		'initializeUnchecked': 'collapsed',
		'collapseDuration': 200,
		'expandDuration': 200
	}).show();
	
	$(window).unload(function(){
		window['bgWindow']['oCatogories']['save']();
	});
});

(function($)  {
   $['fn']['extend']({
	  'setChecked' : function(state)  {
		if (state)
			return this.filter(":radio, :checkbox").attr("checked", true);
		else 
			return this.filter(":radio, :checkbox").removeAttr("checked");
	  },
	  'setVisibility' : function(state)  {
		if (state)
			return this.show();
		else 
			return this.hide();
	  }
   });
}(jQuery));

function renderExceptionsTable(id){
	$('table#' + id + ' tbody').empty()
		.html("<tr><td><a class='url' type='"+id+"'></a></td><td class='centered'><img src='images/icons/delete.png' alt='Удалить' onclick='deleteException(this)'></td></tr>");
	var d = {'tbody tr': {}};
	d['tbody tr']['exception<-' + id] = {'a.url':'exception.url'};
	console.log(d);
	$('table#' + id)['autoRender'](window['bgWindow']['oExceptions'], d);
}

window['deleteException'] = function (node){
	var domainNode = $(node).parent().prev().children(),
		url = domainNode.text(),
		id = domainNode.attr('type')
	window['bgWindow']['oExceptions'][id] = $.grep(window['bgWindow']['oExceptions'][id], function(elem){
		return elem['url'] == url;
	}, true);
	window['bgWindow']['oExceptions'].save();
	renderExceptionsTable(id);
}